<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82882996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\piles;

use think\facade\Db;
use app\common\dao\piles\PilesBasicDao;
use app\common\repositories\BaseRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;

/**
 * Class PilesBasicRepository
 *
 * @mixin PilesBasicDao
 */
class PilesBasicRepository extends BaseRepository
{

    public function __construct(PilesBasicDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'propertyInfo' => function ($query) {
                    $query->field('id,name');
                    $query->bind(['property_name' => 'name']);
                },
            ])
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }

    public function getApiList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->with([
                'planInfo' => function ($query) {
                    $query->field('id,mode_type,basic_price,stair_price');
                },
            ])
            ->field('id,piles_name,piles_type,out_type,port_num,power_rate,address,longitude,latitude,is_online,plan_id')
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }

    public function addInfo(array $data, int $propertyId, int $userId)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $pilesInfo = $this->dao->create($data);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($propertyId, $userId, 'PILES.BASIC.ADD', $data);
            ## 充电桩创建事件
            event('piles.create', [
                'pilesInfo' => $pilesInfo,
                'userId' => $userId
            ]);
            return $pilesInfo;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            ## 充电桩创建事件
            event('piles.upgrade', [
                'pilesInfo' => $info,
                'userId' => $userId
            ]);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'PILES.BASIC.EDIT', $data);

            return $this->dao->update($info['id'], $data);
        });
    }


    public function getDetail(int $id)
    {
        $data = $this->dao->search([])
            ->with([
                'propertyInfo' => function ($query) {
                    $query->field('id,name');
                    $query->bind(['property_name' => 'name']);
                },
            ])
            ->where('id', $id)
            ->find();
        return $data;
    }

    /**
     * 获取充电桩详情
     * @param int $id
     * @return \app\common\model\BaseModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-12 19:52
     */
    public function getApiDetail(int $id)
    {
        $data = $this->dao->getSearch([])
            ->where('id', $id)
            ->where('is_show', 1)
            ->with([
                'planInfo' => function ($query) {
                    $query->field('id,mode_type,basic_price,stair_price');
                },
            ])
            ->field('id,piles_name,piles_type,out_type,port_num,power_rate,address,longitude,latitude,is_online,plan_id')
            ->find();
        return $data;
    }


    public function batchDelete(array $ids, int $userId = 0, string $remark = '')
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids]
        ], 'id,property_id,property_id,piles_name,sim_key');
        if ($list) {
            $num = 0;
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId, $remark);
                $num++;
            }
            return $num;
        }
        return [];
    }

    public function deleteInfo($info, int $userId = 0, string $remark = '')
    {
        return Db::transaction(function () use ($info, $userId, $remark) {
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'PILES.BASIC.DEL', $info);
            ## 充电桩删除事件
            event('piles.delete', [
                'remark' => $remark,
                'pilesInfo' => $info,
                'userId' => $userId
            ]);

            return $this->dao->delete($info['id']);
        });
    }

    public function getPilesData(int $propertyId = null, array $where = [])
    {
        $list = $this->dao->search($where, $propertyId)
            ->field('piles_name label,id value')
            ->select()->toArray();
        return $list;
    }
}